package com.meiyu.live.ui.main;

import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.net.param.GetPageParams;
import com.meiyu.live.net.param.HookupMoreParams;
import com.meiyu.live.net.response.HotLiveResponse;
import com.meiyu.live.popj.LiveRoom;
import com.meiyu.live.tv.audience.AudienceActivity;
import com.meiyu.live.ui.main.widget.AllHotLiveDrawerView;
import com.meiyu.live.util.BitmapHelp;
import com.meiyu.live.widget.MSGView;
import com.meiyu.live.widget.NetLoadingDailog;


/**
 * Created by zbl on 2016/11/18.
 * 正在播出更多界面
 */
public class NowLiveActivity extends BaseActivity implements View.OnClickListener {

    public static final String COLUMN_NAME = "column_name";
    public static final String COLUMN_ID = "column_id";

    private static final int STATE_ALL = 0;
    private static final int STATE_FILTER = 1;

    protected NetLoadingDailog dialog_loading;
    private MSGView msgView;
    private View btn_back, btn_filter, btn_liststyle;
    private ImageView iv_btn_liststyle;
    private TextView tv_title;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private DataListAdapter adapter;
    //    private View footerView;
    private DrawerLayout drawerLayout;
    private AllHotLiveDrawerView allHotLiveDrawerView;

    private static final int PAGE_SIZE = 10;
    private int index = 1;
    private boolean hasMore = true;
    private HotLiveResponse hotLiveResponse = new HotLiveResponse();
    private int filter_id = -1;

    private LayoutInflater inflater;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    RecyclerView.LayoutManager layoutManager0, layoutManager1;

    private String column_name;
    private long column_id;

    private int state = STATE_ALL;
    private int list_state = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_allhotlive);
        init();
    }

    private void init() {
        inflater = LayoutInflater.from(this);
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.image_loading)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.image_loading)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.image_loading)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();

//        column_name = getIntent().getStringExtra(COLUMN_NAME);
        column_name = "正在播出";
        column_id = getIntent().getLongExtra(COLUMN_ID, 0);

        dialog_loading = new NetLoadingDailog(this);
        msgView = (MSGView) findViewById(R.id.msgView);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//        mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.app_name, R.string.app_name) {
//            @Override
//            public void onDrawerClosed(View drawerView) {
//                super.onDrawerClosed(drawerView);
//            }
//
//            @Override
//            public void onDrawerOpened(View drawerView) {
//                super.onDrawerOpened(drawerView);
//            }
//        };
//        drawerLayout.addDrawerListener(mDrawerToggle);
        allHotLiveDrawerView = (AllHotLiveDrawerView) findViewById(R.id.drawer);
        allHotLiveDrawerView.setFilterViewListener(new AllHotLiveDrawerView.FilterViewListener() {
            @Override
            public void onClickOk(int id) {
                dialog_loading.loading();
                filter_id = id;
                if (filter_id >= 0) {
                    getDataByFilter(true);
                } else {
                    getData(true);
                }
                if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
                    drawerLayout.closeDrawer(GravityCompat.END);
                }
            }
        });

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(column_name);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        btn_filter = findViewById(R.id.btn_filter);
        btn_filter.setOnClickListener(this);
        btn_liststyle = findViewById(R.id.btn_liststyle);
        btn_liststyle.setOnClickListener(this);
        iv_btn_liststyle = (ImageView) findViewById(R.id.iv_btn_liststyle);

        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (filter_id >= 0) {
                    getDataByFilter(true);
                } else {
                    getData(true);
                }
            }
        });
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        layoutManager0 = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        layoutManager1 = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        list_state = 0;
        recyclerView.setLayoutManager(layoutManager0);
//        footerView = inflater.inflate(R.layout.view_loadmore, null);
//        recyclerView.addFooterView(footerView);
//        footerView.setVisibility(View.GONE);

        adapter = new DataListAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 判断滚动到底部
                if (isSlideToBottom(recyclerView) && hasMore) {
                    if (filter_id >= 0) {
                        getDataByFilter(false);
                    } else {
                        getData(false);
                    }
                }
            }

            protected boolean isSlideToBottom(RecyclerView recyclerView) {
                if (recyclerView == null) return false;
                if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange())
                    return true;
                return false;
            }
        });

        dialog_loading.loading();
        getData(true);
    }

    @Override
    public void onClick(View view) {
        if (view == btn_filter) {
            if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
                drawerLayout.closeDrawer(GravityCompat.END);
            } else {
                drawerLayout.openDrawer(GravityCompat.END);
            }
        } else if (view == btn_back) {
            finish();
        } else if (view == btn_liststyle) {
            if (list_state == 0) {
                list_state = 1;
                iv_btn_liststyle.setImageResource(R.drawable.ic_btn_liststyle0);
                recyclerView.setLayoutManager(layoutManager1);
            } else {
                list_state = 0;
                iv_btn_liststyle.setImageResource(R.drawable.ic_btn_liststyle1);
                recyclerView.setLayoutManager(layoutManager0);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
            drawerLayout.closeDrawer(GravityCompat.END);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onError() {
        dialog_loading.dismissDialog();
        refreshLayout.setRefreshing(false);
        super.onError();
    }

    private void getData(final boolean reload) {
        if (reload) {
            index = 1;
            hasMore = true;
        }
        int area[] = {PAGE_SIZE, index * PAGE_SIZE};
        GetPageParams gp = new GetPageParams(area);
        gp.setUrl(Constant.VERSION + Constant.UrlParams.LIVES);
        request(gp, HotLiveResponse.class, new Response.Listener<HotLiveResponse>() {
            @Override
            public void onResponse(HotLiveResponse indexAllResponse) {
                dialog_loading.dismissDialog();
                refreshLayout.setRefreshing(false);
                if (indexAllResponse != null) {
                    if (reload) {
                        NowLiveActivity.this.hotLiveResponse.getHash().clear();
                    }
                    NowLiveActivity.this.hotLiveResponse.getHash().addAll(indexAllResponse.getHash());
                    index += 1;
                    if (indexAllResponse.getHash().size() < PAGE_SIZE) {
                        hasMore = false;
                    }
                    adapter.notifyDataSetChanged();
                    if (NowLiveActivity.this.hotLiveResponse.getHash().size() == 0) {
                        msgView.show_empty();
                    } else {
                        msgView.dismiss();
                    }
                } else {
                    msgView.show_error();
                }

            }
        });
    }

    private void getDataByFilter(final boolean reload) {
        if (reload) {
            index = 1;
            hasMore = true;
        }
        int a[] = {PAGE_SIZE, index * PAGE_SIZE};
        HookupMoreParams pageParams = new HookupMoreParams(filter_id, a);
        pageParams.setUrl(Constant.VERSION + Constant.UrlParams.LIVEFILTER);
        request(pageParams, HotLiveResponse.class, new Response.Listener<HotLiveResponse>() {
            @Override
            public void onResponse(HotLiveResponse hotLiveResponse) {
                dialog_loading.dismissDialog();
                refreshLayout.setRefreshing(false);
                if (hotLiveResponse != null) {
                    if (reload) {
                        NowLiveActivity.this.hotLiveResponse.getHash().clear();
                    }
                    NowLiveActivity.this.hotLiveResponse.getHash().addAll(hotLiveResponse.getHash());
                    index += 1;
                    if (hotLiveResponse.getHash().size() < PAGE_SIZE) {
                        hasMore = false;
                    }
                    adapter.notifyDataSetChanged();
                    if (NowLiveActivity.this.hotLiveResponse.getHash().size() == 0) {
                        msgView.show_empty();
                    } else {
                        msgView.dismiss();
                    }
                } else {
                    msgView.show_error();
                }

            }
        });
    }

    class DataListAdapter extends RecyclerView.Adapter<DataListAdapter.ViewHolder> {

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            int res;
            if (list_state == 0) {
                res = R.layout.adapter_nowlive_item0;
            } else {
                res = R.layout.adapter_nowlive_item1;
            }
            View view = inflater.inflate(res, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.layout_root.setTag(position);
            final LiveRoom bean = hotLiveResponse.getHash().get(position);
            imageLoader.displayImage(BitmapHelp.getImgByCdn(bean.getAvatar(), "m_fill", "400", "600"), holder.iv_avatar, options);
            holder.tv_name.setText(bean.getAnchor_name());
            holder.tv_content.setText(TextUtils.isEmpty(bean.getDescription()) ? "无介绍" : bean.getDescription());
            holder.tv_appoint.setText(bean.getViewer_num() + "人正在观看");
        }

        @Override
        public int getItemCount() {
            return hotLiveResponse != null && hotLiveResponse.getHash() != null ? hotLiveResponse.getHash().size() : 0;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public View layout_root;
            public TextView tv_name, tv_content, tv_appoint;
            public ImageView iv_avatar;

            public ViewHolder(View itemView) {
                super(itemView);
                layout_root = itemView.findViewById(R.id.layout_root);
                layout_root.setOnClickListener(onItemClickListener);
                tv_name = (TextView) itemView.findViewById(R.id.tv_name);
                iv_avatar = (ImageView) itemView.findViewById(R.id.iv_avatar);
                tv_content = (TextView) itemView.findViewById(R.id.tv_content);
                tv_appoint = (TextView) itemView.findViewById(R.id.tv_appoint);
            }
        }

        View.OnClickListener onItemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int index = (int) view.getTag();
                final LiveRoom bean = hotLiveResponse.getHash().get(index);
                AudienceActivity.start(NowLiveActivity.this, bean);
            }
        };
    }
}
